from rest_framework import serializers
from .models import *
from products.models import Product
from users.models import Address

class OrderListSerializer(serializers.ModelSerializer):
    product_code = serializers.CharField(source='product.product_code', read_only=True)
    product_title = serializers.CharField(source='product.title', read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    seller_name = serializers.CharField(source='seller.username', read_only=True)
    product_status = serializers.IntegerField(source='product.status', read_only=True)
    cancel_reason = serializers.SerializerMethodField()
    class Meta:
        model = Order
        fields = [
            'id', 'order_code', 'product_code', 'product_title',
            'status', 'status_display', 'seller_name',
            'create_time', 'snapshot_price', 'product_status',
            'payment_time','cancel_reason'
        ]
    def get_cancel_reason(self, obj):
        """从操作日志中获取取消原因"""
        if obj.status == 4:  # 已取消状态
            cancel_log = obj.logs.filter(action='cancel').first()
            return cancel_log.detail if cancel_log else None
        return None
    
    def get_can_operate(self, obj):
        """
        判断当前用户是否可以操作订单
        买家可以操作自己的订单，卖家只能查看
        """
        request = self.context.get('request')
        if not request or not request.user.is_authenticated:
            return False
            
        role = self.context.get('role', 'buyer')
        return role == 'buyer' and obj.buyer == request.user




class OrderCreateSerializer(serializers.ModelSerializer):
    address = serializers.PrimaryKeyRelatedField(
        queryset=Address.objects.all(),
        required=True,
        help_text="收货地址ID"
    )

    class Meta:
        model = Order
        fields = ['product', 'address']
        extra_kwargs = {
            'product': {'required': True}
        }

    def validate(self, attrs):
        """统一验证"""
        # 验证地址属于当前用户
        if attrs['address'].user != self.context['request'].user:
            raise serializers.ValidationError({"address": "无效的收货地址"})
        
        # 验证不能购买自己的商品
        if attrs['product'].seller == self.context['request'].user:
            raise serializers.ValidationError({"product": "不能购买自己的商品"}) 
        return attrs
    
    def create(self, validated_data):
        """创建订单"""
        product = validated_data['product']
        buyer = self.context['request'].user
        
        order = Order.objects.create(
            product=product,
            address=validated_data['address'],
            buyer=buyer,
            seller=product.seller,
            snapshot_price=product.price,
            status=0,
            payment_expire_time=timezone.now() + timedelta(minutes=30)
        )
        return order
    
class OrderStatusSerializer(serializers.Serializer):
    status = serializers.IntegerField()

class OrderLogSerializer(serializers.ModelSerializer):
    operator_name = serializers.CharField(source='operator.username', read_only=True)
    action_display = serializers.CharField(source='get_action_display', read_only=True)

    class Meta:
        model = OrderLog
        fields = [
            'action', 'action_display',
            'operator_name', 'ip_address',
            'created_at', 'detail'
        ]

class ReviewSerializer(serializers.ModelSerializer):
    buyer_username = serializers.CharField(source='buyer.username', read_only=True)
    order_code = serializers.CharField(source='order.order_code', read_only=True)
    rating_display = serializers.CharField(source='get_rating_display', read_only=True)

    class Meta:
        model = Reviews
        fields = [
            'id', 'order', 'order_code', 'buyer', 'buyer_username',
            'content', 'rating', 'rating_display', 'review_time'
        ]
        read_only_fields = ['buyer', 'review_time']
        extra_kwargs = {
            'order': {'required': True, 'write_only': True}
        }

    def validate_order(self, value):
        """验证订单权限和状态"""
        # 仅允许买家操作自己的已完成订单
        if value.buyer != self.context['request'].user:
            raise serializers.ValidationError("无权评论他人订单")
        if value.status != 3:
            raise serializers.ValidationError("订单未完成，不可评价")
        return value

    def validate(self, attrs):
        """检查是否重复评价"""
        if self.instance is None and Reviews.objects.filter(
            order=attrs['order'],
            buyer=self.context['request'].user
        ).exists():
            raise serializers.ValidationError("每个订单只能评价一次")
        return attrs